import { Rectangle } from "./rectangle.js";
import { gameDom, birdDom, scoreDom, landDom, pipeWidth, spaceHeight, pipeMinHeight, getRandom } from "./util.js";

const landStyles = getComputedStyle(landDom);
const landTop = parseFloat(landStyles.top);
const gameWith = gameDom.clientWidth;
const birdLeft = parseFloat(getComputedStyle(birdDom).left);

// 管道类
export class Pipe extends Rectangle {
    constructor(height, top, speed, dom) {
        super(pipeWidth, height, gameWith, top, speed, 0, dom);
    }

    // 移动检测
    onMove() {
        if (this.left < -this.width) {
            this.dom.remove();  // 移除 dom
        }
    }
}


// 柱子
export class PipePare {
    constructor(speed) {
        this.spaceHeight = spaceHeight;
        this.minHeight = pipeMinHeight;
        this.maxHeight = landTop - this.minHeight - this.spaceHeight;

        // 上柱子 
        const uphight = getRandom(this.minHeight, this.maxHeight);
        const updom = document.createElement("div");
        updom.className = "pipe up";
        this.upPipe = new Pipe(uphight, 0, speed, updom);

        // 下柱子
        const downhight = landTop - uphight - this.spaceHeight;
        const downtop = landTop - downhight;
        const downdom = document.createElement("div");
        downdom.className = "pipe down";
        this.downPipe = new Pipe(downhight, downtop, speed, downdom);

        // 添加到地图上
        gameDom.appendChild(updom);
        gameDom.appendChild(downdom);
    }

    // 移除检测 （属性获取）
    get useLess() {
        return this.upPipe.left < -this.upPipe.width;
    }

    // 是否过小鸟
    get birdLeft() {
        return this.upPipe.left < birdLeft;
    }

    move(duration) {
        this.upPipe.move(duration);
        this.downPipe.move(duration);
    }
}

// 产生柱子对
export class PipePareProducer {
    // 产生的
    constructor(speed, gspeed) {
        this.speed = speed;
        this.pairs = [];  // 存放柱子队
        this.timer = null;
        this.tick = 1000;
        this.sunsroce = 0;  // 总分
        this.gspeed = gspeed;
    }

    // 产生柱子
    startProduce() {
        if (this.timer) return
        this.timer = setInterval(() => {
            // 添加柱子数据
            this.pairs.push(new PipePare(this.speed));
            // 移除柱子数据
            this.pairs.forEach((item, index) => {
                // 判断得分
                if (item.birdLeft) {
                    this.sunsroce += this.gspeed;
                    scoreDom.innerHTML = this.sunsroce;  // 显示得分
                }
                // 判断是否离开可视区
                if (item.useLess) {
                    this.pairs.splice(index, 1);
                    index--;
                }
            });
        }, this.tick);
    }

    // 移除柱子
    stopProduce() {
        clearInterval(this.timer)
        this.timer = null;
    }
}